/*TODO: add SIGPIPE handler (EPIPE) */
/**
 * @file main.c
 * @brief
 * @author h0rr0rr_drag0n <h0rr0rr_drag0n@vindekapets.ru
 * @date 18 Июль 2010 22:43:32
 *
 * Client for osd_server. Send to osd server numeric value, 
 * which it take from first commandline argument.
 */

#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include "define.h"

/**
 * @brief echo help
 *
 * This function print help to console
 */
void echo_help(char * argv0) {
    fprintf(stderr, "Usage:\n\t%s numeric_value\n", argv0);
    return;
}

/**
 * @brief Main function
 */
int main(int argc, char * argv[]) {
    int str_pointer = 0;
    int writefd = 0;
    int write_retval = 0;

    if (argc != 2) {
        echo_help(argv[0]);
        return 1;
    }
    /* check - is argv[1] a number */
    while (argv[1][str_pointer] != '\0') {
        if (!isdigit(argv[1][str_pointer])) {
            echo_help(argv[0]);
            return 1;
        }
        str_pointer++;
    }

    if ((writefd = open(FIFO_PATH, O_WRONLY | O_NONBLOCK, 0)) < 0) {
        if (errno == ENXIO) {
            fprintf(stderr, "Error: osd_server not responding! Remove %s?\n",
                    FIFO_PATH);
        } else {
            fprintf(stderr, "Error: open(): %s\n", strerror(errno));
        }
        return 1;
    }

    str_pointer = 0;
    do {
        write_retval = write(writefd, &argv[1][str_pointer], sizeof(char));
        if (write_retval < 0) {
            if (errno == EAGAIN) {
                continue;
            }
            fprintf(stderr, "Error: write(): %s\n", strerror(errno));
            return 1;
        }
    } while (argv[1][str_pointer++] != '\0');

    if (close(writefd) < 0) {
        fprintf(stderr, "Error: close(): %s\n", strerror(errno));
        return 1;
    }

    return 0;
}

